import taskListApi from '../api/taskList'

export default (data, html2canvas, that) => {
  if (!data) return
  taskListApi.getReport({
    diagTaskCode: data.diagTaskCode,
    diagModelCode: data.diagModelCode
  }).then(res => {
    if (res && res.status === 200 && res.data.code === 200) {
      let thisData = res.data.data
      let isShow = document.getElementById('canvas')
      if (isShow) {
        isShow.remove()
      }
      const style = 'width:1000px; background:#fff; padding:100px; padding-top:0; font-family:"微软雅黑"'
      const newNode = document.createElement('div')
      if (window.navigator.msSaveOrOpenBlob) {
        newNode.style.cssText = style
      } else {
        newNode.style = style
      }
      newNode.id = 'canvas'
      const html = '<div>' +
          '<div style="display:inline-block; width:100%;">' +
            '<p style="line-height:100px; font-size:50px; font-weight:bold;color:#37405E;text-align:center; font-family:' + "微软雅黑" + ';">' + thisData.title + '</p>' +
            '<div style="color:#000; font-size:18px; background:#f5f5f5; padding:20px; line-height:30px; padding-left:60px; font-family:' + "微软雅黑" + '; font-weight: bold;color:#616161;">' +
              '<p>单位名称：' + thisData.companyName + '</p>' +
              '<p>场站名称：' + thisData.stationName + '</p>' +
              '<p>巡检任务编号：' + thisData.inspectTaskCode + '</p>' +
              '<p>诊断任务编号：' + thisData.diagTaskCode + '</p>' +
              '<p>诊断模型：' + thisData.diagModelName + '</p>' +
              '<p>诊断时间：' + thisData.diagDay + '</p>' +
              '<p>图片总数：' + thisData.totalPicNum + '</p>' +
              '<p>故障图片数量：' + thisData.totalDefectivePicNum + '</p>' +
              '<p>故障总数：' + thisData.totalDefectiveNum + '</p>' +
            '</div>' +
          '</div>' +
        '</div>' +
        '<p style="color:#37405E; font-size:25px;font-weight:bold;margin-top:30px;margin-bottom:20px;">缺陷位置</p>' +
        '<div style="border-top:2px solid #e4e4e4;border-right:2px solid #e4e4e4; width:800px; box-sizing:border-box;">' +
          returnStr(thisData.picAndLocationDTO, thisData.diagModelName) +
        '</div>'
        newNode.innerHTML = html
        const node = document.querySelector('body')
        node.appendChild(newNode)
        html2canvas(document.getElementById('canvas')).then(function(canvas) {
          const dataUrl = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream")
          if (window.navigator.msSaveOrOpenBlob) {
            const blob_ = dataURLtoBlob(dataUrl)
            window.navigator.msSaveBlob(blob_, '下载.png')
            document.body.removeChild(newNode)
          } else {
            const dataURL = canvas.toDataURL("image/png")
            // const oA = document.createElement("a")
            // oA.download = ''
            // window.open(dataURL)
            // oA.style.display = 'none'
            // document.body.appendChild(oA)
            // oA.click()
            // oA.remove()
            // newNode.remove()
            console.log(canvas, dataURL, dataUrl);
            var a = document.createElement('a')
            a.download = ''
            a.innerHTML = 'download'
            a.style.display = 'none'
            a.href = URL.createObjectURL(dataURLtoBlob(dataURL))
            // a.onclick = function() {
            //   requestAnimationFrame(function() {
            //     URL.revokeObjectURL(a.href)
            //   })
            //   a.removeAttribute('href')
            // }
            a.click()
            a.remove()
            newNode.remove()
          }
        })
    } else {
      that.$message.error(res.data.message)
    }
  }).catch(err => {
    that.$message.error('接口请求失败！')
  })
}
function dataURLtoBlob(dataurl) {
  const arr = dataurl.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const	bstr = window.atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}
function returnStr (data, type) {
  if (!data) return
  let str = ''
  data.map(item => {
    str += `<div style="width:100%;position:relative; padding-right:350px; border-bottom:2px solid #e4e4e4;border-left:2px solid #e4e4e4;">
      ${returnleftItem(item.defectivePosition)}
      <div style="padding:25px; position:absolute; top:0; right:0; width:350px">

        <div style="display: inline-block;vertical-align: top;width:99%;">
          <p style="font-size:20px; color:#616161;word-wrap:break-word; line-height:26px; margin-bottom:10px;">${type === '割草验收' ? '可见光图' : '红外光图'}: ${item.dataResultPicName}</p>
          <img src="${'data:image/jpeg;base64,' + item.dataResultPath}" style="width:300px; height:300px;" />
        </div>

      </div>
    </div>
    `
  })
  return str
}
// ${
//   type !== '割草验收' ? '<div style="display: inline-block;vertical-align: top;width:49%;">' +
//     '<p style="font-size:20px; color:#616161;word-wrap:break-word; line-height:26px;">可见光图: ' + item.visiblePicName + '</p>' +
//     '<img src="data:image/jpeg;base64,' + item.visibleDataPath + '" style="width:210px; height:230px;" />' +
//   '</div>' : ''
// }
function returnleftItem(data) {
  if (!data) return ''
  let str = '<div style="width: 390px; min-height:400px;border-right: 2px solid #e4e4e4;">'
  data.map((item, idx) => {
    str += `
    <div style="padding: 20px;font-size: 18px;">
      <p style="font-size:20px; font-weight:600; color:#37405E; margin-bottom:20px;">缺陷位置${idx + 1}：</p>
      <p style="line-height:30px;">
        经纬度：${item.defectivePosition}
      </p>
      <p style="line-height:30px;">
        所在光伏组件编码：${item.pvModuleCode}
      </p>
      <p style="line-height:30px;">
        经纬度：${item.centerLatLong}
      </p>
    </div>
    `
  })
  str += '</div>'
  return str
}
